package com.brush.brushcommon.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.brush.brushcommon.handerl.CustomException;
import com.brush.brushcommon.redis.service.RedisService;
import com.brush.brushcommon.vo.basic.VerifyCodeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.UUID;

import static com.brush.brushcommon.redis.RedisConstants.LOGIN_CAPTCHA_KEY;
import static com.brush.brushcommon.redis.RedisConstants.LOGIN_CAPTCHA_TTL;

@Slf4j
@Component
public class CaptchaImageUtil {

    private static RedisService redisService;

    public CaptchaImageUtil(RedisService redisService) {
        this.redisService = redisService;
    }


    /**
     * 生成验证码
     * @return
     */
    public static VerifyCodeVO getVerifyThree() {
        String captchaKey = UUID.randomUUID().toString();
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(150, 40, 5, 0);
        // 存入redis并设置过期时间为30分钟
        redisService.set(LOGIN_CAPTCHA_KEY + captchaKey, shearCaptcha.getCode(), LOGIN_CAPTCHA_TTL);
        //captcha:d6e561a6-7929-4469-8154-008710932f61
        String base64String = "";
        try {
            base64String = "data:image/png;base64," + shearCaptcha.getImageBase64();
        } catch (Exception e) {
            e.printStackTrace();
        }
        VerifyCodeVO verifyCodeVO = new VerifyCodeVO();
        verifyCodeVO.setCaptchaKey(captchaKey);
        verifyCodeVO.setCaptchaImg(base64String);
        return verifyCodeVO;
    }


    /**
     *  校验验证码
     * @param captchaKey 验证码key也就是uuid
     * @param captchaValue
     * @return
     */
        public static boolean verify(String captchaKey, String captchaValue) {
            String key = LOGIN_CAPTCHA_KEY + captchaKey;
            if(!redisService.hasKey(key)){
                throw new CustomException(500,"验证码已过期");
            }
            String redisCode= redisService.get(key).toString().toLowerCase();
            log.info("redisCode里的验证码：" + redisCode);
            String receivedCode = captchaValue.toLowerCase();
            System.out.println("用户的验证码：" + receivedCode);
            return !"".equals(redisCode) && !"".equals(receivedCode) && redisCode.equals(receivedCode);
        }

}
